<?php

namespace app\admin\controller;

use think\Db;

/**
 * 栏目辅助类
 * 用于处理栏目相关的数据库操作和权限检查
 */
class ColumnHelper
{
    /**
     * 检查fa_column表是否有userid字段
     * @return bool
     */
    public static function hasUseridField()
    {
        static $hasField = null;
        
        if ($hasField === null) {
            try {
                $columns = Db::query("SHOW COLUMNS FROM fa_column LIKE 'userid'");
                $hasField = !empty($columns);
            } catch (\Exception $e) {
                $hasField = false;
            }
        }
        
        return $hasField;
    }
    
    /**
     * 安全地获取栏目的userid字段
     * @param array $column 栏目数据
     * @return int|null
     */
    public static function getColumnUserId($column)
    {
        if (self::hasUseridField() && isset($column['userid'])) {
            return $column['userid'];
        }
        return null;
    }
    
    /**
     * 安全地设置栏目的userid字段
     * @param array &$params 参数数组
     * @param int $userId 用户ID
     */
    public static function setColumnUserId(&$params, $userId)
    {
        if (self::hasUseridField()) {
            $params['userid'] = $userId;
        }
    }
    
    /**
     * 检查用户是否是栏目的创建者
     * @param array $column 栏目数据
     * @param int $userId 用户ID
     * @return bool
     */
    public static function isColumnOwner($column, $userId)
    {
        $columnUserId = self::getColumnUserId($column);
        return $columnUserId && $columnUserId == $userId;
    }
}